package us.kg.kotoriforest.schedule.dao.impl;

import us.kg.kotoriforest.schedule.dao.BaseDAO;
import us.kg.kotoriforest.schedule.dao.SysUserDAO;
import us.kg.kotoriforest.schedule.pojo.SysUser;

import java.sql.SQLException;
import java.util.List;

/**
 * ClassName: us.kg.kotoriforest.schedule.dao.impl.SysUserDAOImpl </br>
 * Description: sys_user 表的 DAO 实现类
 *
 * @author Kotori rotroutine@163.com
 * @since 2024/12/1
 */
public class SysUserDAOImpl extends BaseDAO implements SysUserDAO {
    @Override
    public SysUser selectByUid(int uid) throws RuntimeException {
        SysUser sysUser = null;
        String sql = "SELECT uid, username, user_pwd AS userPwd from sys_user WHERE uid = ?";
        try {
            sysUser = executeQueryGetFirstElement(SysUser.class, sql, uid);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return sysUser;
    }

    @Override
    public List<SysUser> selectAll() {
        List<SysUser> sysUsers = null;
        String sql = "SELECT uid, username, user_pwd AS userPwd from sys_user";
        try {
            sysUsers = executeQuery(SysUser.class, sql);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return sysUsers;
    }

    @Override
    public int insert(SysUser user) {
        String sql = "INSERT INTO sys_user(username, user_pwd) VALUES(?, ?)";
        int rows = 0;
        try {
            rows = executeUpdate(sql, user.getUsername(), user.getUserPwd());
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return rows;
    }

    @Override
    public int update(SysUser user) {
        int rows = 0;
        String sql = "UPDATE sys_user SET username = ?, user_pwd = ? WHERE uid = ?";
        try {
            rows = executeUpdate(sql, user.getUsername(), user.getUserPwd(), user.getUid());
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return rows;
    }

    @Override
    public int deleteByUid(int uid) {
        int rows = 0;
        String sql = "DELETE FROM sys_user WHERE uid = ?";
        try {
            rows = executeUpdate(sql, uid);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return rows;
    }

    @Override
    public int countAll() {
        int rows = 0;
        String sql = "SELECT COUNT(*) FROM sys_user";
        try {
            rows = executeQueryGetBasicElement(Integer.class, sql);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return rows;
    }

    @Override
    public SysUser selectByUsername(String username) {
        SysUser sysUser = null;
        String sql = "SELECT uid, username, user_pwd AS userPwd from sys_user WHERE username = ?";
        try {
            sysUser = executeQueryGetFirstElement(SysUser.class, sql, username);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return sysUser;
    }
}
